package com.yhsoft.common.service;

import com.alibaba.fastjson2.JSON;
import com.yhsoft.common.Enum.CommonCodeEnum;
import com.yhsoft.common.service.Po.TokenUser;
import com.yhsoft.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.util.Base64;

/**
 * token验证处理
 *
 * @author yyyyyyyh
 * @since 2023-09-20
 * */
@Component
public class TokenService {
    @Autowired
    private JwtUtil jwtUtil;

    public static String getCurrentToken() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        String token = request.getHeader("X-Token");
        return token;
    }

    public static TokenUser getUserBytoken(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        String token = request.getHeader("Authorization");
        if(StringUtils.isEmpty(token)){
            throw new RuntimeException("获取token失败！");
        }
        if (StringUtils.isNotEmpty(token) && token.startsWith("Bearer")) {
            token = token.replace("Bearer", "");
        }
        TokenUser loginUser = null;
        try {
            //loginUser = parseToken(token, User.class);
            byte[] encode = Base64.getEncoder().encode(CommonCodeEnum.JWT_KEY.getCode().getBytes());

            Claims body = Jwts.parser()
                    .setSigningKey(new SecretKeySpec(encode, 0, encode.length, "AES"))
                    .parseClaimsJws(token)
                    .getBody();
            loginUser = JSON.parseObject(body.getSubject(), TokenUser.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return loginUser;
    }

    /**
     * 获取请求token
     *
     * @return token
     */
    public static String getAuthorizationToken() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        String token = request.getHeader("Authorization");
        if(StringUtils.isEmpty(token)){
            throw new RuntimeException("获取token失败！");
        }
        if (StringUtils.isNotEmpty(token) && token.startsWith("Bearer")) {
            token = token.replace("Bearer", "");
        }
        return token;
    }
}
